package com.ruyuan.payment.system.controller.admin;

import com.alibaba.fastjson.JSON;
import com.ruyuan.payment.server.req.UserLoginReq;
import com.ruyuan.payment.server.resp.CommonResp;
import com.ruyuan.payment.server.resp.UserLoginResp;
import com.ruyuan.payment.server.service.UserService;
import com.ruyuan.payment.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/user")
public class AdminUserController {

    private static final Logger LOG = LoggerFactory.getLogger(AdminUserController.class);

    @Resource
    private UserService userService;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public CommonResp login(@RequestBody @Valid UserLoginReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        UserLoginResp userLoginResp = userService.login(req);

        String token = String.valueOf(snowFlake.nextId());
        userLoginResp.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(userLoginResp), 3600, TimeUnit.SECONDS);
        LOG.info("生成token: {}", token);

        CommonResp<UserLoginResp> commonResp = new CommonResp<>();
        commonResp.setContent(userLoginResp);
        return commonResp;
    }

    @DeleteMapping("/logout/{token}")
    public CommonResp login(@PathVariable String token) {
        redisTemplate.delete(token);
        LOG.info("从redis中删除token: {}", token);
        return new CommonResp();
    }

}
